﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using CSCSN.EntitiyModels;
using CSCSN.ORM;
using CSCSN.WebApplication.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Text;
using System.IO;
using System.Collections;
using Microsoft.EntityFrameworkCore.Storage;
using CSCSN.ViewModels;
using System.Collections.Immutable;
using Microsoft.AspNetCore.Authorization;

namespace CSCSN.WebApplication.Controllers
{

    public class PersonCentrelController : Controller
    {
        private readonly CsDbContext db;

        public PersonCentrelController(CsDbContext logger)

        {
            db = logger;
        }
        #region 用户信息
        public IActionResult Index()
        {

            var item = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            var a = item.Id;
            var id = db.ApplicationUserDatas.Where(s => s.ApplicationUsers.Id == a).FirstOrDefault();
            UserDataVM dd = new UserDataVM();
            userDataVM(id, dd);
            ViewData["Name"] = item.Name;
            ViewData["UserName"] = item.UserName;
            return View(dd);

        }
        #endregion

        #region 新增个人资料
        public IActionResult Creat(Guid ID)
        {
            ViewBag.userID = ID;
            return View();
        }
        [HttpPost]
        public ActionResult Creat(UserDataVM dd,Guid id)
        {
            var a = db.ApplicationUsers.Where(s => s.Id == id).FirstOrDefault();
            ApplicationUserData data = new ApplicationUserData();              
            data = TaskToModel(dd,data);      
            data.ApplicationUsers= new ApplicationUser();
            data.ApplicationUsers = a;
            db.ApplicationUserDatas.Add(data);
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        #endregion

        #region 修改个人信息  
        public IActionResult Update()
        {
            var item = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            var a = item.Id;
            var id = db.ApplicationUserDatas.Where(s => s.ApplicationUsers.Id == a).FirstOrDefault();
            UserDataVM dd = new UserDataVM();
            userDataVM(id, dd);
            ViewData["date"] = id.Birthday.Date.ToString("yyyy - MM - dd");
            ViewData["ClassName"] = id.ClassName;
            ViewData["College"] = id.College;
            ViewData["Name"] = item.Name;
            ViewData["UserName"] = item.UserName;
            return View(dd);
        }
        [HttpPost]
        public IActionResult Update(UserDataVM userData)
        {
            ApplicationUserData applicationUser = new ApplicationUserData();
            application(userData, applicationUser);
            db.ApplicationUserDatas.Update(applicationUser);
            db.SaveChanges();
            return RedirectToAction("Update", "PersonCentrel");
        }
        #endregion

        #region 头像编辑
        public IActionResult Edit()
        {
            var item = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            var id = db.ApplicationUserDatas.Where(s => s.ApplicationUsers.Id == item.Id).FirstOrDefault();
            UserDataVM dd = new UserDataVM();
            userDataVM(id, dd);
            return View(dd);
        }
        [HttpPost]
        public ActionResult Edit(UserDataVM dd)
        {
            var item = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            var a = item.Id;
            var id = db.ApplicationUserDatas.Where(s => s.ApplicationUsers.Id == a).FirstOrDefault();
            try
            {
                // TODO: Add insert logic here
                try
                {
                    /*var form = Request.Form;*///直接从表单里面获取文件名不需要参数
                                                //string dd = IngURL["File"];
                    /* var form = IngURL*/
                    ;//定义接收类型的参数
                    Hashtable hash = new Hashtable();
                    IFormFileCollection cols = Request.Form.Files;
                    if (cols == null || cols.Count == 0)
                    {

                        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                        Response.WriteAsync(" <script> alert('未上传文件！');window.location.href = '/PersonCentrel/Edit'</script> ", Encoding.GetEncoding("GB2312"));

                    }
                    foreach (IFormFile file in cols)
                    {

                        //定义图片数组后缀格式
                        string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
                        //获取图片后缀是否存在数组中
                        string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
                        if (LimitPictureType.Contains(currentPictureExtension))
                        {
                            if (file.Length < 3145728)
                            {
                                //为了查看图片就不在重新生成文件名称了
                                //var new_path = DateTime.Now.ToString("yyyyMMdd") + file.FileName;
                                var time = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                                var new_path = Path.Combine("Image/头像/", time + file.FileName);
                                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", new_path);

                                using (var stream = new FileStream(path, FileMode.Create))
                                {
                                    string imgurl = "/" + new_path;

                                    //图片公开
                                    userDataVM(id, dd);
                                    id.HeadPortrait = imgurl;
                                    db.ApplicationUserDatas.Update(id);
                                    db.SaveChanges();
                                    //    //再把文件保存的文件夹中
                                    file.CopyTo(stream);
                                    hash.Add("file", "/" + new_path);
                                }
                            }
                            else
                            {
                                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                                Response.WriteAsync("<script> alert('上传的图片大小要小于3M!');window.location.href = '/PersonCentrel/Creat'</script>", Encoding.GetEncoding("GB2312"));
                            }
                        }
                        else
                        {
                            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                            Response.WriteAsync("<script> alert('请上传指定格式的图片!');window.location.href = '/PersonCentrel/Creat'</script>", Encoding.GetEncoding("GB2312"));

                        }
                    }

                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    Response.WriteAsync("<script> alert('图片上传成功!');window.location.href = '/PersonCentrel/Edit'</script>", Encoding.GetEncoding("GB2312"));
                }
                catch (Exception ex)
                {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    Response.WriteAsync("<script> alert('图片上传失败!');window.location.href = '/PersonCentrel/Creat'</script>", Encoding.GetEncoding("GB2312"));
                }
                return View();
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 辅导员发布任务
       [Authorize(Roles = "Counselor")]//角色授权：角色类型Counselor才能访问

        public IActionResult CreatTask()
        {
            ViewBag.ApplicationTaskTypesID = new SelectList(db.ApplicationTaskTypes, "Id", "Name");//
            ViewBag.TaskSiteID = new SelectList(db.TaskSites, "Id", "Name");//下拉
            ViewBag.IssuerID = new SelectList(db.ApplicationRoles, "Id", "Name");//下拉
            return View();
        }
        [HttpPost]
        public IActionResult CreatTask(ApplicationTaskVM aa)
        {
            if (ModelState.IsValid)
            {
                db.ApplicationTasks.Add(MapToModel(aa));
                db.SaveChanges();
            }

            return RedirectToAction("Index","Home");
        }
        #endregion

        #region 数据映射

        private ApplicationUserData TaskToModel(UserDataVM model, ApplicationUserData item)
        {
            //ApplicationUser application = new ApplicationUser();
            //application = model.ApplicationUsers;
            //item.ApplicationUsers = application;         
            item.Id = new Guid();
            item.Hobby = model.Hobby;
            item.Age = model.Age;
            item.Birthday = model.Birthday;
            item.HeadPortrait = model.HeadPortrait;
            item.Sex = model.Sex;
            item.ClassName = model.ClassName;
            item.College = model.College;
            item.RealName = model.RealName;
            item.Phone = model.Phone;
            item.StudentNumber = model.StudentNumber;
            item.HeadPortrait = "/Photo/0.png";
            return item;
        }
        private ApplicationUserData application(UserDataVM model, ApplicationUserData item)
        {
            var dd = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            item.Id = model.Id;
            item.Hobby = model.Hobby;
            item.Age = model.Age;
            item.Birthday = model.Birthday;
            item.HeadPortrait = model.HeadPortrait;
            item.Sex = model.Sex;
            item.ClassName = model.ClassName;
            item.College = model.College;
            item.RealName = model.RealName;
            item.Phone = model.Phone;
            item.StudentNumber = model.StudentNumber;
            item.HeadPortrait = "/Photo/0.png";
            dd.Name = model.Name;
            return item;
        }

        private UserDataVM userDataVM(ApplicationUserData model, UserDataVM item)
        {
            var dd = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            item.Id = model.Id;
            item.Hobby = model.Hobby;
            item.Age = model.Age;
            item.Birthday = model.Birthday;
            item.HeadPortrait = model.HeadPortrait;
            item.Sex = model.Sex;
            item.ClassName = model.ClassName;
            item.College = model.College;
            item.RealName = model.RealName;
            item.Phone = model.Phone;
            item.StudentNumber = model.StudentNumber;
            item.Name = dd.Name;
            return item;
        }
        private ApplicationTask MapToModel(ApplicationTaskVM model)
        {
            ApplicationTask item = new ApplicationTask();
            item.Name = model.Name;
            item.TaskSites = db.TaskSites.Find(model.TaskSiteID);
            item.Score = model.Score;
            item.BeginTime = model.BeginTime;
            var users = db.ApplicationUsers.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
            var dd = db.UserRoles.Where(s => s.UserId == users.Id).FirstOrDefault();
            item.IssuerID = dd.RoleId;
            item.Duration = model.Duration;
            item.ApplicationTaskTypesID = model.ApplicationTaskTypesID;
            return item;
        }
        #endregion


    }
}
